package com.llkj.qingnianguoxue.circle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.jm.call.CallActivity;
import com.jm.chat.activity.ChatActivity;
import com.jm.chat.application.JGApplication;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.MemSilenceBean;
import com.llkj.qingnianguoxue.bean.Response;
import com.llkj.qingnianguoxue.bean.RxBusChatBean;
import com.llkj.qingnianguoxue.bean.RxChatMsgBean;
import com.llkj.qingnianguoxue.bean.response.ResponseData;
import com.llkj.qingnianguoxue.http.AnsynHttpRequest;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.music.MusicDetailActivity;
import com.llkj.qingnianguoxue.util.DateUtils;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetGroupInfoCallback;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;
import rx.functions.Action1;

public class MyChatActivity extends ChatActivity implements AnsynHttpRequest.ObserverCallBack{
    private long mSilenceTime = -1;
    public static final String APP_KEY = "d2177a685bbde53285409f35";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initListener();
        RxBus.getInstance().toObservable(String.class).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals(ConstantUserInfo.REFRESH_CIRCLE)){
                    finish();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(StringUtils.isEmpty(mTargetId)){
            String circleId = getIntent().getStringExtra("CircleId");//圈子id
            HttpMethod.circleIsAnExcuse(this,this,circleId);
        }

    }

    private void initListener(){
        RxBus.getInstance().toObservable(String.class).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                if (s.equals(ConstantUserInfo.REFRESH_CIRCLE)){//退出群组
                    finish();
                }
            }
        });
        RxBus.getInstance().toObservable(RxBusChatBean.class).subscribe(new Action1<RxBusChatBean>() {
            @Override
            public void call(RxBusChatBean bean) {
                if (1==bean.getType()){
                    getChatView().setChatTitle(bean.getContent());
                    RxBus.getInstance().post(ConstantUserInfo.REFRESH_CIRCLE_NAME);
                }
            }
        });
        RxBus.getInstance().toObservable(Message.class).subscribe(new Action1<Message>() {
            @Override
            public void call(Message msg) {
                    //设置需要已读回执
                    MessageSendingOptions options = new MessageSendingOptions();
                    options.setNeedReadReceipt(true);
                    JMessageClient.sendMessage(msg, options);
                    mChatAdapter.addMsgFromReceiptToList(msg);
            }
        });

    }

    @Override
    public void inviteFriendClick(View view,final TextContent textContent) {
        super.inviteFriendClick(view,textContent);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String circleId = textContent.getStringExtra("circleId");
                String musicId = textContent.getStringExtra("musicId");
                if(!StringUtils.isEmpty(circleId)){
                    Intent bundle = new Intent(MyChatActivity.this,CircleDetailActivity.class);
                    bundle.putExtra("circleId",circleId);
                    startActivity(bundle);
                }else if(!StringUtils.isEmpty(musicId)){
                    String musicPath = textContent.getStringExtra("musicPath");
                    if(!StringUtils.isEmpty(musicPath)){

                    }else{
                        Intent bundle = new Intent(MyChatActivity.this,MusicDetailActivity.class);
                        bundle.putExtra("musicId",musicId);
                        startActivity(bundle);
                    }
                }
            }
        });

    }

    public static void startSingleChat(Activity context, String title, String chatId, String uid){
        Intent intent = new Intent();
        intent.putExtra(JGApplication.CONV_TITLE,title);
        intent.putExtra(JGApplication.TARGET_APP_KEY, "d2177a685bbde53285409f35");
        intent.putExtra(JGApplication.TARGET_ID, chatId);
        intent.putExtra("uid", uid);
        intent.setClass(context, MyChatActivity.class);
        context.startActivity(intent);
    }

    public static void startGroupChat(Activity context,String groupId,String circleId,String groupName) {
        try{
            Intent intent = new Intent();
            intent.putExtra(JGApplication.CONV_TITLE, groupName);
            intent.putExtra(JGApplication.GROUP_ID, Long.parseLong(groupId));
            intent.putExtra("CircleId",circleId);
            intent.setClass(context, MyChatActivity.class);
            context.startActivity(intent);
        }catch (Exception e){}
    }

    @Override
    public void startChatDetailActivity(Activity context,String targetId, String appKey, long groupId) {
        if(!StringUtils.isEmpty(targetId)){//单聊
            String uid = getIntent().getStringExtra("uid");
            Intent intent = new Intent(context,CircleOwnerDetailActivity.class);
            intent.putExtra("ownerId",uid);
            intent.putExtra("BottomBtn","1");
            startActivity(intent);
        }else{//群聊
            String circleId = getIntent().getStringExtra("CircleId");
            Intent intent = new Intent(context,GroupDetailActivity.class);
            intent.putExtra("circleId",circleId);
            context.startActivity(intent);
        }
    }

    @Override
    protected void startTackVoice() {
        super.startTackVoice();
        Intent intent = new Intent(this,CallActivity.class);
        intent.putExtra("ChatId",mTargetId);
        startActivity(intent);
    }

    @Override
    public void handleResult(String data, int encoding, int method) {
        switch (encoding) {
            case AnsynHttpRequest.SUCCESS_HTTP:
                if (method == HttpMethod.HTTP_CIRCLE_INDEX) {
                    try {
                        MemSilenceBean silenceBean = GsonUtil.GsonToBean(data,MemSilenceBean.class);
                        if(silenceBean!=null){
                            if(silenceBean.getState()==1){
                                if("1".equals(silenceBean.getIs_jin())){
                                    mSilenceTime = DateUtils.dateFormat(silenceBean.getEnd_time()).getTime();
                                    if(mSilenceTime<=System.currentTimeMillis()){
                                        setSilence();
                                    }else{

                                    }
                                }
                            }
                        }
                    }catch (Exception e){}
                }
                break;
            case AnsynHttpRequest.FAILURE_HTTP:

                break;
            case AnsynHttpRequest.FAILURE_NETWORK:

                break;
        }

    }

    private void setSilence(){
        //设置群成员禁言状态
        JMessageClient.getGroupInfo(mGroupId, new GetGroupInfoCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage, GroupInfo groupInfo) {
                if (0 == responseCode) {
                    String chatId = MyApplication.getInstance().sputil.getString(ConstantUserInfo.CHAT_LOGIN_ID);
                    groupInfo.setGroupMemSilence(chatId, "", true, new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            if (0 == i) {
                                Log.e("Log","取消禁言成功");
                            } else {
//                                ToastUtil.makeLongText(MyChatActivity.this,"取消禁言失败");
                            }
                        }
                    });
                } else {
//                                            Toast.makeText(getApplicationContext(), keepSilence ? "设置禁言失败" : "取消禁言失败", Toast.LENGTH_SHORT).show();
                    Log.e("Log", "getGroupInfo failed " + ", responseCode = " + responseCode + " :Desc = " + responseMessage);
                }
            }
        });
    }
}
